package com.example.managemyself.data.repository;

import android.app.Application;
import androidx.lifecycle.LiveData;
import com.example.managemyself.data.database.AppDatabase;
import com.example.managemyself.data.database.HealthDao;
import com.example.managemyself.data.model.HealthData;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class HealthRepository {
    
    private HealthDao healthDao;
    private ExecutorService executor;
    
    public HealthRepository(Application application) {
        AppDatabase database = AppDatabase.getInstance(application);
        healthDao = database.healthDao();
        executor = Executors.newSingleThreadExecutor();
    }
    
    public HealthRepository(android.content.Context context) {
        AppDatabase database = AppDatabase.getInstance(context);
        healthDao = database.healthDao();
        executor = Executors.newSingleThreadExecutor();
    }
    
    public LiveData<List<HealthData>> getAllHealthData() {
        return healthDao.getAllHealthData();
    }
    
    public LiveData<HealthData> getHealthDataByDate(Date date) {
        return healthDao.getHealthDataByDate(date);
    }
    
    public void insertOrUpdate(HealthData healthData) {
        executor.execute(() -> {
            HealthData existing = healthDao.getHealthDataByDateSync(healthData.getDate());
            if (existing != null) {
                healthData.setId(existing.getId());
                healthDao.update(healthData);
            } else {
                healthDao.insert(healthData);
            }
        });
    }
    
    public void insert(HealthData healthData) {
        executor.execute(() -> healthDao.insert(healthData));
    }
    
    public void update(HealthData healthData) {
        executor.execute(() -> healthDao.update(healthData));
    }
    
    public void delete(HealthData healthData) {
        executor.execute(() -> healthDao.delete(healthData));
    }
    
    // 同步方法供AIDataManager使用
    public List<HealthData> getRecentHealthDataSync(int days) {
        try {
            return healthDao.getRecentHealthDataSync(days);
        } catch (Exception e) {
            return new java.util.ArrayList<>();
        }
    }
} 